package transform;

import beans.SenSorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class RichFunctionTest {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //从文件中读取数据
        DataStreamSource<String> inputStream = env.readTextFile("src/main/resources/sensor.txt");

        SingleOutputStreamOperator<SenSorReading> dataStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SenSorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });

        DataStream<Tuple2<String, Integer>> res = dataStream.map(new MyMapper());

        res.print();
        env.execute();
    }

    public static class MyMapper01 implements MapFunction<SenSorReading, Tuple2<String, Integer>> {

        @Override
        public Tuple2<String, Integer> map(SenSorReading senSorReading) throws Exception {
            return new Tuple2<>(senSorReading.getId(), senSorReading.getId().length());
        }
    }

    /**
     * 主要的作用就是可以获取到当前的很多运行时信息
     */
    //实现自定义富函数类
    public static class MyMapper extends RichMapFunction<SenSorReading, Tuple2<String, Integer>> {

        @Override
        public Tuple2<String, Integer> map(SenSorReading senSorReading) throws Exception {
            return new Tuple2<>(senSorReading.getId(), getRuntimeContext().getIndexOfThisSubtask()+1);
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            /**
             * 初始化的工作,一般是定义工作状态,或者建立数据库连接
             */
            System.out.println("open");
        }

        @Override
        public void close() throws Exception {
            /**
             * 释放缓存，关闭连接
             */
            System.out.println("close");
        }
    }
}
